import BuyRecord from '../../../database/models/buyRecord'
import {PlayerModel} from '../../../database/models/player'

export const typeDefs = `

  type PlayerInfo{
    _id: String!
    name:String!
    coin: Int!
    freeCoin: Int!
    gem: Int!
    point: Int!
    headImgUrl:String!
    shortId:Int!
  }
  type ProductPrice{
    goldPrice: Int
    rubyPrice: Int
  }

  type BuyRecord{
    _id: String!
    product: String!
    productName: String!
    productPrice: ProductPrice!
    state: String!
    player:  PlayerInfo!
    createAt: String!
    state: String!
    
    phone: String
    wechat:String
    delivery:String
  }
`


export const queryDefs = `
  buyRecordsByPage(page:Int!,player:String) :[BuyRecord]!
`

export const mutationDefs = `
  updateBuyRecordTo(recordId:String!,state:String):BuyRecord
  setBuyRecordDelivery(recordId:String!,delivery:String!):BuyRecord
  deleteBuyRecord(recordId:String!): Boolean
`

export const resolvers = {

  Query: {
    async buyRecordsByPage(_, {page = 0, player}) {

      console.log(`${__filename}:51 buyRecordsByPage`, page, player);
      const shortId = parseInt(player)
      let critia = {}
      if (shortId) {
        console.log(`${__filename}:56 buyRecordsByPage  xxx `, player);
        const p = await PlayerModel.findOne({shortId})
        if (p) critia = {player: p._id}
        else {
          return []
        }
      }

      return BuyRecord.find(critia)
        .skip(page * 10).limit(10)
        .sort({createAt: -1})
        .populate('player', {})
    }
  },


  Mutation: {
    async updateBuyRecordTo(_, {recordId, state}) {
      const br = await BuyRecord.findById(recordId).populate('player')
      br.state = state
      await br.save()
      return br
    },

    async setBuyRecordDelivery(_, {recordId, delivery}) {
      const br = await BuyRecord.findById(recordId).populate('player')
      br.delivery = delivery
      await br.save()
      return br
    },

    async deleteBuyRecord(_, {recordId}) {
      await BuyRecord.remove({_id: recordId})
      return true
    }

  }
}
